from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QListWidget,
                             QHBoxLayout, QPushButton, QInputDialog)


class CategoryManager(QDialog):
    def __init__(self, model, parent=None):
        super().__init__(parent)
        self.model = model
        self.setWindowTitle("分类管理")
        self.setup_ui()

    def setup_ui(self):
        layout = QVBoxLayout()

        # 分类列表
        self.list_widget = QListWidget()
        self.refresh_categories()
        layout.addWidget(self.list_widget)

        # 操作按钮
        btn_layout = QHBoxLayout()
        self.add_btn = QPushButton("添加分类")
        self.add_btn.clicked.connect(self.add_category)
        btn_layout.addWidget(self.add_btn)

        self.rename_btn = QPushButton("重命名")
        self.rename_btn.clicked.connect(self.rename_category)
        btn_layout.addWidget(self.rename_btn)

        self.remove_btn = QPushButton("删除分类")
        self.remove_btn.clicked.connect(self.remove_category)
        btn_layout.addWidget(self.remove_btn)

        layout.addLayout(btn_layout)
        self.setLayout(layout)

    def refresh_categories(self):
        self.list_widget.clear()
        self.list_widget.addItems(sorted(self.model.categories))
        self.list_widget.addItem("未分类")  # 特殊项

    def add_category(self):
        name, ok = QInputDialog.getText(self, "添加分类", "分类名称:")
        if ok and name.strip():
            if name.strip() not in self.model.categories:
                self.model.categories.add(name.strip())
                self.refresh_categories()

    def rename_category(self):
        item = self.list_widget.currentItem()
        if not item or item.text() == "未分类":
            return

        new_name, ok = QInputDialog.getText(
            self, "重命名分类",
            "新名称:",
            text=item.text())

        if ok and new_name.strip():
            # 更新数据库中的分类
            with self.model.session_factory.session() as session:
                for feed in session.query(Feed).filter(Feed.category == item.text()):
                    feed.category = new_name.strip()
                session.commit()

            self.model.categories.remove(item.text())
            self.model.categories.add(new_name.strip())
            self.refresh_categories()

    def remove_category(self):
        item = self.list_widget.currentItem()
        if not item or item.text() == "未分类":
            return

        # 将关联feed移入未分类
        with self.model.session_factory.session() as session:
            for feed in session.query(Feed).filter(Feed.category == item.text()):
                feed.category = None
            session.commit()

        self.model.categories.remove(item.text())
        self.refresh_categories()